#!/bin/bash

source ~/.bashrc
source ~/.bash_profile

hostIp=172.16.x.x
username=default
passwd=xxx
clustername=cluster1_3shards_1replicas
dbname=snc_aiops_performance
tbname="local_exception_event local_metric_uint local_metric_text local_metric_dbl"
tbname_2="local_quick_trace"

function clear_data() {
        name=$1
	tna=$2
        check_day=`date -d '-5 days' '+%F'`
        integer_day_ts=`date -d $name '+%s'`
        check_day_ts=`date -d $check_day '+%s'`
        if [ $integer_day_ts -lt $check_day_ts ];then
            sqldrop="alter table $dbname.$tna ON CLUSTER $clustername drop partition '$name'"
            #echo $sqldrop
            clickhouse-client -h $hostIp --user $username --password $passwd -q "$sqldrop"
        else
            echo "not enough days, skip..."
        fi
}

function clear_data_2() {
	#二级分区: (20241113,'2024-11-13')
        name2=$1
        tna2=$2
        check_day=`date -d '-90 days' '+%F'`
	#截取一级分区
	integer_day=`echo "$name2" | cut -b 2-9`
        integer_day_ts=`date -d $integer_day '+%s'`
        check_day_ts=`date -d $check_day '+%s'`
        if [ $integer_day_ts -lt $check_day_ts ];then
            sqldrop="alter table $dbname.$tna2 ON CLUSTER $clustername drop partition $name2"
            #echo $sqldrop
            clickhouse-client -h $hostIp --user $username --password $passwd -q "$sqldrop"
	else
            echo "not enough days, skip..."
        fi

}


function delete_table() {
    dn=$1
    tn=$2
    sqlcx="SELECT partition FROM system.parts where database='$dn' and table='$tn'"
    clickhouse-client -h $hostIp --user $username --password $passwd -q "$sqlcx" | while read LINE
    do
        sleep 1
        clear_data $LINE $tn
    done

}

function delete_table_2() {
    dn=$1
    tn2=$2
    sqlcx="SELECT partition FROM system.parts where database='$dn' and table='$tn2'"
    clickhouse-client -h $hostIp --user $username --password $passwd -q "$sqlcx" | while read LINE
    do
        #sleep 1
        clear_data_2 $LINE $tn2
    done

}

function one_partition() {
    for tn in ${tbname}
    do
        echo $tn
        delete_table $dbname $tn
    done

}

function two_partition() {
    for tn2 in ${tbname_2}
    do
        echo "开始删除:$tn2"
        delete_table_2 $dbname $tn2
    done

}

one_partition
two_partition
